//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import type { LocalRepoInfo, HeadInfo } from "@/api/local_repo";
import { list_repo, get_head_info, list_git_filter } from "@/api/local_repo";
import { Button, Form, message, Segmented, Tabs } from "antd";
import ChangeBranchOrTagModal from "./components/ChangeBranchOrTagModal";
import { DownloadOutlined, UploadOutlined } from "@ant-design/icons";
import PushModal from "./components/PushModal";
import PullModal from "./components/PullModal";
import WorkDir from "./components/WorkDir";
import { list_widget, type WidgetInfo } from "@/api/widget";
import { request } from "@/utils/request";
import ChangeFileList from "./components/ChangeFileList";
import LargeFileList from "./components/LargeFileList";
import CommitList from "./components/CommitList";
import GitInfo from "./components/GitInfo";
import { get_global_server_addr } from "@/api/client_cfg";
import type { USER_TYPE } from "@/api/user";


const GitSimpleApp = () => {
    const location = useLocation();
    const urlParams = new URLSearchParams(location.search);
    const repoId = urlParams.get("id") ?? "";
    const userName = urlParams.get("username") ?? "";
    const userType = parseInt(urlParams.get("usertype") ?? "0") as USER_TYPE;
    const userToken = urlParams.get("token") ?? "";

    const [repoInfo, setRepoInfo] = useState<LocalRepoInfo | null>(null);
    const [headInfo, setHeadInfo] = useState<HeadInfo | null>(null);
    const [filterList, setFilterList] = useState<string[]>([]);
    const [activeKey, setActiveKey] = useState("workDir");
    const [widgetList, setWidgetList] = useState<WidgetInfo[]>([]);

    const [showChangeBranchOrTagModal, setShowChangeBranchOrTagModal] = useState(false);
    const [showPullModal, setShowPullModal] = useState(false);
    const [showPushModal, setShowPushModal] = useState(false);

    const [commitShowType, setCommitShowType] = useState<"list" | "graph">("list");

    const loadRepoInfo = async () => {
        const repoInfoList = await list_repo();
        const tmpRepoInfo = repoInfoList.find(item => item.id == repoId);
        if (tmpRepoInfo == undefined) {
            message.error("Git仓库不存在");
            return;
        }
        setRepoInfo(tmpRepoInfo);
        const tmpHeadInfo = await get_head_info(tmpRepoInfo.path);
        setHeadInfo(tmpHeadInfo);
        const tmpFilterList = await list_git_filter(tmpRepoInfo.path);
        setFilterList(tmpFilterList);
    };

    const loadWidgetList = async () => {
        const addr = await get_global_server_addr();
        const res = await request(list_widget(addr));
        setWidgetList(res.widget_list.sort((a, b) => b.weight - a.weight));
    };

    useEffect(() => {
        loadWidgetList();
        loadRepoInfo();
    }, []);

    return (
        <>
            {repoInfo != null && headInfo != null && (
                <Tabs activeKey={activeKey} onChange={key => setActiveKey(key)} type="card"
                    tabBarStyle={{ height: "40px" }}
                    tabBarExtraContent={
                        <Form layout="inline">
                            {headInfo.detached == false && (
                                <Form.Item label="当前分支">
                                    <Button type="link" onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setShowChangeBranchOrTagModal(true);
                                    }}>{headInfo.branch_name}</Button>
                                </Form.Item>
                            )}

                            {headInfo.detached == true && (
                                <Form.Item label="当前标记">
                                    <Button type="link" onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setShowChangeBranchOrTagModal(true);
                                    }}>{headInfo.tag_name}</Button>
                                </Form.Item>
                            )}

                            {activeKey == "workDir" && (headInfo?.branch_name ?? "") != "" && (
                                <>
                                    <Form.Item>
                                        <Button type="primary" icon={<DownloadOutlined style={{ fontSize: "20px" }} />} title="拉取(pull)"
                                            style={{ borderRadius: "6px" }}
                                            onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setShowPullModal(true);
                                            }} >
                                            Pull
                                        </Button>
                                    </Form.Item>
                                    <Form.Item>
                                        <Button type="primary" icon={<UploadOutlined style={{ fontSize: "20px" }} />} title="推送(push)"
                                            style={{ borderRadius: "6px" }}
                                            onClick={e => {
                                                e.stopPropagation();
                                                e.preventDefault();
                                                setShowPushModal(true);
                                            }} >
                                            Push
                                        </Button>
                                    </Form.Item>
                                </>
                            )}
                            {activeKey == "commit" && (
                                <Form.Item label="显示方式">
                                    <Segmented options={[{
                                        label: "列表",
                                        value: "list"
                                    },
                                    {
                                        label: "图形",
                                        value: "graph",
                                    }]} value={commitShowType} onChange={value => setCommitShowType(value as "list" | "graph")} />
                                </Form.Item>
                            )}
                        </Form>
                    }>
                    <Tabs.TabPane key="workDir" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>工作目录</span>} >
                        {activeKey == "workDir" && (
                            <div>
                                <WorkDir basePath={repoInfo.path} headCommitId={headInfo?.commit_id ?? ""} widgetList={widgetList} />
                                <ChangeFileList repo={repoInfo} />
                            </div>
                        )}
                    </Tabs.TabPane>
                    <Tabs.TabPane key="commit" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>提交记录</span>}>
                        {activeKey == "commit" && headInfo != null && (
                            <CommitList repo={repoInfo} headInfo={headInfo} showType={commitShowType} />
                        )}
                    </Tabs.TabPane>
                    <Tabs.TabPane key="gitInfo" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>Git信息</span>}>
                        {activeKey == "gitInfo" && (
                            <GitInfo repo={repoInfo} headInfo={headInfo} userType={userType} userToken={userToken}/>
                        )}
                    </Tabs.TabPane>
                    {filterList.includes("lfs") && (
                        <Tabs.TabPane key="lfs" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>大文件列表</span>}>
                            {activeKey == "lfs" && (
                                <LargeFileList repoPath={repoInfo.path} />
                            )}
                        </Tabs.TabPane>
                    )}
                </Tabs>
            )}
            {showChangeBranchOrTagModal == true && repoInfo != null && headInfo != null && (
                <ChangeBranchOrTagModal headInfo={headInfo} repo={repoInfo}
                    onCancel={() => setShowChangeBranchOrTagModal(false)}
                    onOk={() => {
                        setShowChangeBranchOrTagModal(false);
                        get_head_info(repoInfo.path).then(res => setHeadInfo(res));
                    }} />
            )}
            {showPullModal == true && repoInfo != null && (
                <PullModal repoPath={repoInfo.path} headBranch={headInfo?.branch_name ?? ""} onClose={() => setShowPullModal(false)} userName={userName} />
            )}
            {showPushModal == true && repoInfo != null && (
                <PushModal repoPath={repoInfo.path} headBranch={headInfo?.branch_name ?? ""} onClose={() => setShowPushModal(false)} userName={userName} />
            )}
        </>
    );
};

export default GitSimpleApp;